
open Histo
open Glob.Bin

let fit_slices proj ~n ~f ~select:i hist =
    let h = get_2d hist in
    let axis = match proj with X -> h.H2.xa | Y -> h.H2.ya in
    let range = Axis.range axis in
    let min = Axis.min axis in
    let slices = List.map (fun i ->
        let i' = float i and width = range /. float n in
        min +. i' *. width, min +. (i'+.1.) *. width
    ) ( 0--(n-1) )
    in
    let proj_hists = 
        let proj_h2 h2 r =
            let p = match proj with X -> Y | Y -> X in
            H2.projection p (
                    match proj with 
                      X -> H2.sub ~except_last:true ~x:(Some r) ~y:None h2
                    | Y -> H2.sub ~except_last:true ~x:None ~y:(Some r) h2
            )
        in
        Array.of_list (List.map (fun (c1,c2) -> 
            0.5*.(c1+.c2), (proj_h2 h (c1,c2))) slices)
    in
(*
    let _,h1 = proj_hists.(4) in
    (H1d h1)
    *)
    
    let graph = H1.h {n=n;x1=min;x2=Axis.max axis} 
        { name = h.H2.info.name^(letter proj); 
          title = h.H2.info.title^" slices "^(letter proj) }
    in
(*    let calc_result h =
        let res,err,_,_ = f (H1d h) in
        res.(i)
    in*)
    let results_errors = Array.map (fun (c,h) ->
        let res,err,_,_ = f (H1d h) in
        c,res.(i),err.(i)
    ) proj_hists in
    Array.iter (fun (x,y,_) -> H1.fill x y graph) results_errors;
    let sq_errors = Array.map (fun (_,_,err) -> err**2.) results_errors in
    H1.set_sq_errors graph sq_errors;
    (*
    Array.iter (fun (c,h) -> 
        H1.fill c (calc_result h) graph
    ) proj_hists;*)
    H1d graph


